package nyist.media.controller;

import lombok.extern.slf4j.Slf4j;
import nyist.media.config.shiro.filter.AuthenticationFilter;
import nyist.media.utils.RSAUtils;
import org.apache.commons.codec.binary.Base64;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.security.interfaces.RSAPublicKey;

/**
 * @author dcf
 */
@Controller
@RequestMapping("/login")
@Slf4j
public class LoginController {

    @RequestMapping
    public String toLogin(HttpServletRequest request, Model model) {
        try {
            Subject subject = SecurityUtils.getSubject();
            if (subject.isAuthenticated()) {
                return "redirect:" + "/admin/index";
            }
            RSAPublicKey publicKey = RSAUtils.generateKey(request);
            String modulus = Base64.encodeBase64String(publicKey.getModulus().toByteArray());
            String exponent = Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray());
            model.addAttribute("modulus", modulus);
            model.addAttribute("exponent", exponent);
            model.addAttribute("message", request.getAttribute(AuthenticationFilter.LOGIN_FAIL_MSG_PARAM_NAME));
            return "/login";
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "/common/error";
        }
    }
}
